package com.example.download.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import javax.xml.ws.Response;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {
    static String LOCAL_PATH="E:\\kange\\";

    @GetMapping("/download/{fileName}")
    public ResponseEntity<Resource> getFile(@PathVariable("fileName") Serializable fileName) {
        // 转换路径为Path对象
        String ACTUAL_PATH=LOCAL_PATH+fileName;

        Path imageFilePath = Paths.get(ACTUAL_PATH);

        // 检查文件是否存在
        if (!Files.exists(imageFilePath)) {
            return ResponseEntity.notFound().build();
        }

        // 读取文件内容
        try {
            Resource resource = new FileSystemResource(imageFilePath);


            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            String contentType = Files.probeContentType(imageFilePath);
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
            MediaType mediaType = MediaType.parseMediaType("application/octet-stream");
            headers.setContentType(mediaType);
            // 返回图片资源
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(Files.size(imageFilePath))
                    .body(resource);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }



    }

    @GetMapping("/delete/{fileName}")

    public Boolean deleteFile(@PathVariable("fileName") Serializable fileName){
        // 转换路径为Path对象
        String ACTUAL_PATH=LOCAL_PATH+fileName;
        File file = new File(ACTUAL_PATH); // 替换为你的文件路径

        if (file.delete()) {
           return true;
        } else {
            return false;
        }
    }

}
